package edu.unh.sustain;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class FeedHandler extends DefaultHandler {

    private static final String TAG = "FeedHandler";

    private List<Video>         videos;
    private Video               currentVideo;
    private StringBuilder       builder;

    public List<Video> getVideos() {
        return this.videos;
    }

    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        super.characters(ch, start, length);
        builder.append(ch, start, length);
    }

    @Override
    public void endElement(String uri, String localName, String name)
            throws SAXException {
        super.endElement(uri, localName, name);
        if (this.currentVideo != null) {
            if (name.equalsIgnoreCase(VideoFeedParser.TITLE)) {
                currentVideo.setTitle(builder.toString());
            } else if (name.equalsIgnoreCase(VideoFeedParser.DESCRIPTION)) {
                currentVideo.setDescription(builder.toString());
            } else if (name.equalsIgnoreCase(VideoFeedParser.MEDIA_GROUP)) {
                currentVideo.setDescription(builder.toString());
            } else if (name.equalsIgnoreCase(VideoFeedParser.ENTRY)) {
                videos.add(currentVideo);
            }
            builder.setLength(0);
        }
    }

    @Override
    public void startDocument() throws SAXException {
        super.startDocument();
        videos = new ArrayList<Video>();
        builder = new StringBuilder();
    }

    @Override
    public void startElement(String uri, String localName, String name,
            Attributes attributes) throws SAXException {
        super.startElement(uri, localName, name, attributes);
        if (localName.equalsIgnoreCase(VideoFeedParser.ENTRY)) {
            this.currentVideo = new Video();
        } else if (name.equalsIgnoreCase(VideoFeedParser.LINK)) {
            try {
                currentVideo.setUrl(attributes.getValue(0));
            } catch (MalformedURLException e) {
                e.printStackTrace();
            }
        }
    }
}
